import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 线索飞书 (单线索)监听 群机器人
 *
 * @author wangsong
 * @date 2023/04/10
 */
@Slf4j
public class FenShuMsgApi {


    /**
     * 测试环境
     */
    private static final String TEST_URL = "https://open.feishu.cn/open-apis/bot/v2/hook/9eedb36a-9f0c-4e99-a381-24ffcee1198e";
    private static final String TEST_SECRET = "zHgyPJDq9bPqRig8WMCiYe";


    /**
     * 发送线索接口消息
     *
     * @param content 内容
     * @return boolean
     */
    public static boolean sendMsg(String content) {
        Map<String, Object> contentMap = new HashMap<>(4);
        contentMap.put("text", content);
        sendMsg(contentMap);
        return true;
    }


    private static void sendMsg(Map<String, Object> contentMap) {

        // 发送消息
        // 加签
        long timestamp = System.currentTimeMillis() / 1000;
        String sign = genSign(TEST_SECRET, timestamp);
        // 拼接消息体
        Map<String, Object> paramMap = new HashMap<>(4);
        paramMap.put("timestamp", timestamp);
        paramMap.put("sign", sign);
        paramMap.put("msg_type", "text");
        paramMap.put("content", contentMap);
        // 请求
        String res = HttpRequest.post(TEST_URL)
                .header("Content-Type", "application/json;charset=utf-8")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("发送飞书消息: " + res);

    }

    /**
     * 签名
     *
     * @param secret 秘密
     * @param timestamp 时间戳
     * @return {@link String}
     * @throws NoSuchAlgorithmException 没有这样算法异常
     * @throws InvalidKeyException 无效关键例外
     */
    private static String genSign(String secret, long timestamp) {
        //把timestamp+"\n"+密钥当做签名字符串
        String stringToSign = timestamp + "\n" + secret;

        //使用HmacSHA256算法计算签名
        Mac mac = null;
        try {
            mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        byte[] signData = mac.doFinal(new byte[]{});
        return Base64Encoder.encode(signData);
    }

    public static void main(String[] args) {
        String content = "【异常监控】" +
                "\n系统异常了, 请及时检查测试信息\n " +
                "123" +
                "\n456" +
                "\n678";
        FenShuMsgApi.sendMsg(content);
    }
}
